package com.aurora.oa.login.presenter;

import android.content.Context;
import android.content.SharedPreferences;

import com.aurora.oa.application.MyApplication;
import com.aurora.oa.login.model.LoginResultData;
import com.aurora.oa.listener.OnLoginListener;
import com.aurora.oa.login.model.UserInfo;
import com.aurora.oa.login.view.ILoginView;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.utils.Des3;
import com.aurora.oa.utils.SharedPreferencesUtil;


/**
 * 登录逻辑操作
 */
public class LoginPresenter {
    private ILoginView mLoginView;
    private RequestHttpModel requestHttpModel;
    private Context context;
    public LoginPresenter(Context context,ILoginView loginView) {
        this.context = context;
        mLoginView =loginView;
        requestHttpModel = new RequestHttpModelImpl();
    }

    //处理登录逻辑
    public void doLogin(String userName, String passWord) {
        mLoginView.showProgress();
        //Model层处理登录操作
        requestHttpModel.doLogin(userName,passWord, new OnLoginListener() {
            @Override
            public void onLoginSuccess(LoginResultData loginInfo) {
                mLoginView.onLoginSuccess();
                mLoginView.hideProgress();
                //登录成功记录登录人信息
                if (loginInfo!=null){
                    MyApplication.getInstance().setLoginUser(loginInfo.getObj());
                }else{
                    MyApplication.getInstance().setLoginUser(new UserInfo());
                }

            }

            @Override
            public void onLoginFail(String loginInfo) {
                mLoginView.onLoginFail(loginInfo);
                mLoginView.hideProgress();
            }
        });

    }

    public void saveLoginInfo(String userName, String password){

        SharedPreferencesUtil.saveString(context,SharedPreferencesUtil.USER_NAME,userName);
        SharedPreferencesUtil.saveString(context,SharedPreferencesUtil.PASS_WORD,password);
        String token = "";
        try {
            token = Des3.encode(userName+";"+password);
            SharedPreferencesUtil.saveString(context,SharedPreferencesUtil.TOKEN,token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showLoginInfo() {

        mLoginView.showLoginInfo(SharedPreferencesUtil.getString(context,SharedPreferencesUtil.USER_NAME),SharedPreferencesUtil.getString(context,SharedPreferencesUtil.PASS_WORD));
    }
}
